<script lang="ts">
export default {
  name: 'role',
};
</script>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { Search, Plus, Refresh, Delete } from '@element-plus/icons-vue';
import {
  ArgumentQuery,
  Argument,
  ArgumentTypeForm,
} from '@/api/system/argument/types';
import {
  configPages,
  configAdd,
  configEdit,
  configDel,
} from '@/api/system/argument';
const emit = defineEmits(['roleClick']);
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const resourceRef = ref(ElTree);

const state = reactive({
  loading: true,
  // 选中ID
  ids: [] as number[],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  } as ArgumentQuery,
  roleList: [] as Argument[],
  total: 0,
  dialog: {
    title: '',
    visible: false,
  } as DialogType,
  formData: {} as ArgumentTypeForm,
  rules: {
    configName: [
      { required: true, message: '请输入参数类型', trigger: 'blur' },
    ],
  },
  allocationDialogVisible: false,
  resourceOptions: [] as OptionType[],
  // 勾选的菜单ID
  checkedMenuIds: new Set([]),
  // 选中的角色
  checkedRole: {
    id: '',
    name: '',
  },
});

const {
  ids,
  loading,
  queryParams,
  roleList,
  total,
  dialog,
  formData,
  rules,
  allocationDialogVisible,
  checkedRole,
  resourceOptions,
} = toRefs(state);

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  configPages(state.queryParams).then(({ data }) => {
    roleList.value = data.list;
    total.value = data.total;
    loading.value = false;
  });
}
/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
}

function handleRowClick(row: any) {
  emit('roleClick', row);
}

function handleAdd() {
  dialog.value = {
    title: '添加参数',
    visible: true,
  };
}

function handleUpdate(row: any) {
  dialog.value = {
    title: '修改参数',
    visible: true,
  };
  nextTick(() => {
    state.formData.configValue = ''
    state.formData = Object.assign({}, row);
    console.log(state.formData);
  });
}

function modelValue(val: any) {
  state.formData.configValue = val;
}
function handleSubmit() {
  loading.value = true;
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.formData.configId) {
        configEdit(state.formData).then(() => {
          ElMessage.success('修改参数成功');
          closeDialog();
          handleQuery();
          loading.value = false;
        });
      } else {
        configAdd(state.formData).then(() => {
          ElMessage.success('新增参数成功');
          closeDialog();
          handleQuery();
          loading.value = false;
        });
      }
    }
  });
}

/**
 * 删除
 */
function handleDelete(row: any) {
  const ids = [row.configId || state.ids].join(',');
  if (!ids) {
    ElMessage.warning('请勾选删除项');
    return;
  }

  ElMessageBox.confirm(`确认删除已选中的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      configDel(ids)
        .then(() => {
          handleQuery();
          ElMessage.success('删除成功');
        })
        .catch(() => {
          console.log(`删除失败`);
        });
    })
    .catch(() => ElMessage.info('已取消删除'));
}
/**
 * 取消
 */
function closeDialog() {
  dialog.value.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="configName" label="参数类型">
          <el-input v-model="queryParams.configName" placeholder="请输入参数类型" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card>
      <template #header>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
      </template>

      <el-table ref="dataTableRef" v-loading="loading" :data="roleList" @selection-change="handleSelectionChange" @row-click="handleRowClick" highlight-current-row border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="参数类型" prop="configName" min-width="150" />
        <el-table-column label="内容" prop="configValue" width="150">
          <template #default="scope">
            <!-- <span>{{scope.row.configValue}}</span> -->
            <el-tooltip placement="top">
              <template v-slot:content>
                <p style="max-width:500px;">{{scope.row.configValue}}</p>
              </template>
              <span class="ellipsis" v-if="scope.row.configValue">{{ scope.row.configValue }}</span>
              <span class="ellipsis" v-else>/</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="updateTime" label="修改时间" width="160" />

        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click.stop="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- pagination -->
      <pagination v-if="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- dialog -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" @close="closeDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="参数类型" prop="configName">
          <el-input v-model="formData.configName" placeholder="参数类型" />
        </el-form-item>
        <WangEditor @update:modelValue="modelValue" :modelValue="formData.configValue"></WangEditor>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
:deep(.ellipsis) {
  display: block;
  width: 150px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>